import json
from mycelery import app
from tools.myredis import mredis
from tools.bdapi import bdapi
import time
from order.models import OrderModel
from user.models import UserModel


# 定时任务，取消未支付订单
@app.task
def cancleorders():
    # 从队列中获取信息
    clist = mredis.zset_zrangebyscore('ordercancle', 0, int(time.time()) - 600)
    # 遍历
    if clist:
        for i in clist:
            orderno = i.decode()
            print(orderno)
            print('取消未支付订单任务开启')
            # 更新订单状态
            OrderModel.objects.filter(order_no=int(orderno)).update(order_status=4)
            # 更新用户积分
            order = OrderModel.objects.filter(order_no=int(orderno)).first()
            user = order.user
            total = float(order.total_price)
            tscore = user.tscore
            UserModel.objects.filter(id=user.id).update(tscore=tscore - (total / 10))
            # 恢复优惠券，更新库存

            mredis.zset_zrem('ordercancle', orderno)


# 定时任务,获取redis身份证队列
@app.task
def c_idcard():
    if mredis.list_llen('idcard_list'):
        for i in range(10):
            idcard = mredis.list_pop('idcard_list')
            print(idcard)
            if idcard:
                print('身份证识别任务开始执行')
                res = bdapi.idcard(idcard.decode())
                if res:
                    mredis.str_set(idcard.decode(), json.dumps(res))
                    print('------------------>', mredis.str_get(idcard.decode()))
                print('身份证识别任务执行完毕')
    else:
        print('身份证识别任务队列为空，等待10秒')
        time.sleep(10)


# 定时任务1
@app.task
def my_crontab(x, y):
    print(x, y)
    print('x和y 相加 = {x+y}')
    return x + y


# 定时任务2
@app.task
def my_print():
    print('2222222222222')


@app.task
def c_test1():
    """无参数的异步任务"""
    # print('任务：c_test1执行了...')
    return '异步任务c_test1执行了...'


@app.task(name="c_test2")
def c_test2(name, age):
    """有参数的异步任务"""
    print(f'异步任务：c_test2执行了...name={name}, age={age}')
